<template>
  <div class="delivery-fee-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>配送费规则管理</h2>
      <p class="page-desc">管理店铺的配送费规则，设置基础配送距离、费用等参数</p>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">
        新增配送费规则
      </el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0" icon="el-icon-delete">
        批量删除
      </el-button>
      <el-button @click="handleRefresh" icon="el-icon-refresh">
        刷新
      </el-button>
      <el-button type="success" @click="openCalculator" icon="el-icon-calculator">
        配送费计算器
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="规则名称">
          <el-input v-model="searchForm.ruleId" placeholder="请输入规则名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.isActive" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
          <el-button @click="handleReset" icon="el-icon-refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%">
        
        <el-table-column type="selection" width="55"></el-table-column>
        
        <el-table-column prop="ruleId" label="规则名称" min-width="120">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isActive === 1 ? 'success' : 'info'">
              {{ scope.row.ruleId }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="baseDistance" label="基础配送距离" width="120">
          <template slot-scope="scope">
            {{ scope.row.baseDistance }} 公里
          </template>
        </el-table-column>
        
        <el-table-column prop="baseFee" label="基础配送费" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.baseFee }}
          </template>
        </el-table-column>
        
        <el-table-column prop="extraUnitDistance" label="计费单位距离" width="120">
          <template slot-scope="scope">
            {{ scope.row.extraUnitDistance }} 公里
          </template>
        </el-table-column>
        
        <el-table-column prop="extraUnitFee" label="每单位额外费用" width="140">
          <template slot-scope="scope">
            ¥{{ scope.row.extraUnitFee }}
          </template>
        </el-table-column>
        
        <el-table-column prop="maxDistance" label="最大配送距离" width="120">
          <template slot-scope="scope">
            {{ scope.row.maxDistance ? scope.row.maxDistance + ' 公里' : '无限制' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="isActive" label="状态" width="80">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isActive === 1 ? 'success' : 'info'">
              {{ scope.row.isActive === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="300" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)" icon="el-icon-edit">
              编辑
            </el-button>
            <el-button 
              size="mini" 
              :type="scope.row.isActive === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
              :icon="scope.row.isActive === 1 ? 'el-icon-close' : 'el-icon-check'">
              {{ scope.row.isActive === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)" icon="el-icon-delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
        </el-pagination>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="600px"
      @close="handleDialogClose">
      
      <el-form 
        :model="formData" 
        :rules="formRules" 
        ref="formRef" 
        label-width="140px"
        @submit.native.prevent>
        
        <el-form-item label="规则名称" prop="ruleId">
          <el-input 
            v-model="formData.ruleId" 
            placeholder="请输入规则名称"
            @blur="checkRuleName">
          </el-input>
        </el-form-item>
        
        <el-form-item label="基础配送距离" prop="baseDistance">
          <el-input-number 
            v-model="formData.baseDistance" 
            :min="0.01" 
            :max="100"
            :precision="2"
            :step="0.1"
            placeholder="请输入基础配送距离">
          </el-input-number>
          <span class="unit-text">公里</span>
        </el-form-item>
        
        <el-form-item label="基础配送费" prop="baseFee">
          <el-input-number 
            v-model="formData.baseFee" 
            :min="0" 
            :max="1000"
            :precision="2"
            :step="0.5"
            placeholder="请输入基础配送费">
          </el-input-number>
          <span class="unit-text">元</span>
        </el-form-item>
        
        <el-form-item label="计费单位距离" prop="extraUnitDistance">
          <el-input-number 
            v-model="formData.extraUnitDistance" 
            :min="0.01" 
            :max="10"
            :precision="2"
            :step="0.1"
            placeholder="请输入计费单位距离">
          </el-input-number>
          <span class="unit-text">公里</span>
        </el-form-item>
        
        <el-form-item label="每单位额外费用" prop="extraUnitFee">
          <el-input-number 
            v-model="formData.extraUnitFee" 
            :min="0" 
            :max="100"
            :precision="2"
            :step="0.5"
            placeholder="请输入每单位额外费用">
          </el-input-number>
          <span class="unit-text">元</span>
        </el-form-item>
        
        <el-form-item label="最大配送距离" prop="maxDistance">
          <el-input-number 
            v-model="formData.maxDistance" 
            :min="0" 
            :max="100"
            :precision="2"
            :step="0.5"
            placeholder="请输入最大配送距离（可选）"
            :disabled="formData.noLimit">
          </el-input-number>
          <span class="unit-text">公里</span>
          <el-checkbox v-model="formData.noLimit" @change="handleNoLimitChange">无限制</el-checkbox>
        </el-form-item>
        
        <el-form-item label="启用状态" prop="isActive">
          <el-radio-group v-model="formData.isActive">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="配送费计算示例">
          <div class="calculation-example">
            <p>基础费用：{{ formData.baseFee || 0 }}元（{{ formData.baseDistance || 0 }}公里内）</p>
            <p>超出部分：每{{ formData.extraUnitDistance || 0 }}公里加收{{ formData.extraUnitFee || 0 }}元</p>
            <p v-if="formData.maxDistance && !formData.noLimit">最大配送距离：{{ formData.maxDistance }}公里</p>
            <p v-if="formData.noLimit">最大配送距离：无限制</p>
          </div>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 配送费计算器 -->
    <el-drawer
      title="配送费计算器"
      :visible.sync="calculatorVisible"
      direction="rtl"
      size="400px">
      
      <div class="calculator-content">
        <el-form label-width="100px">
          <el-form-item label="配送距离">
            <el-input-number 
              v-model="calculatorForm.distance" 
              :min="0.01" 
              :max="100"
              :precision="2"
              :step="0.1"
              placeholder="请输入配送距离">
            </el-input-number>
            <span class="unit-text">公里</span>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="calculateDeliveryFee" :loading="calculateLoading">
              计算配送费
            </el-button>
          </el-form-item>
        </el-form>
        
        <div v-if="calculationResult" class="calculation-result">
          <el-divider content-position="left">计算结果</el-divider>
          <div class="result-item">
            <span class="result-label">配送距离：</span>
            <span class="result-value">{{ calculatorForm.distance }} 公里</span>
          </div>
          <div class="result-item">
            <span class="result-label">配送费用：</span>
            <span class="result-value price">¥{{ calculationResult }}</span>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { 
  getDeliveryFeeRuleList, 
  getDeliveryFeeRuleById, 
  addDeliveryFeeRule, 
  updateDeliveryFeeRule, 
  deleteDeliveryFeeRule, 
  deleteDeliveryFeeRuleBatch,
  enableDeliveryFeeRule,
  disableDeliveryFeeRule,
  calculateDeliveryFee,
  checkRuleName
} from '@/api/deliveryFeeRule'
import { getInfo } from "@/api/login";
import { getShopInfo } from "@/api/shop/shopInfo";

export default {
  name: 'DeliveryFeeView',
  data() {
    return {
      // 搜索表单
      searchForm: {
        ruleId: '',
        isActive: ''
      },
      
      // 表格数据
      tableData: [],
      loading: false,
      selectedIds: [],
      
      // 分页
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      
      // 对话框
      dialogVisible: false,
      dialogTitle: '',
      isEdit: false,
      
      // 表单数据
      formData: {
        id: null,
        ruleId: '',
        shopId: null,
        baseDistance: 3,
        baseFee: 5,
        extraUnitDistance: 1,
        extraUnitFee: 2,
        maxDistance: 10,
        isActive: 1,
        noLimit: false
      },
      
      // 表单验证规则
      formRules: {
        ruleId: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        baseDistance: [
          { required: true, message: '请输入基础配送距离', trigger: 'blur' }
        ],
        baseFee: [
          { required: true, message: '请输入基础配送费', trigger: 'blur' }
        ],
        extraUnitDistance: [
          { required: true, message: '请输入计费单位距离', trigger: 'blur' }
        ],
        extraUnitFee: [
          { required: true, message: '请输入每单位额外费用', trigger: 'blur' }
        ]
      },
      
      // 提交状态
      submitLoading: false,
      
      // 计算器
      calculatorVisible: false,
      calculatorForm: {
        distance: 5
      },
      calculationResult: null,
      calculateLoading: false,
      
      // 新增属性
      isRefreshingShopId: false, // 防止重复刷新shopId
      localShopId: null, // 本地存储shopId
    }
  },
  
  computed: {
    // 确保 shopId 正确获取
    currentShopId() {
      // 优先使用本地存储的shopId
      if (this.localShopId) {
        return this.localShopId;
      }
      
      // 其次使用store中的shopId
      if (this.$store.state.user.shopId) {
        this.localShopId = this.$store.state.user.shopId;
        return this.localShopId;
      }
      
      // 都没有则从后端获取
      this.refreshShopId();
      return null;
    }
  },
  
  created() {
    this.initShopId()
  },
  
  methods: {
    // 初始化shopId
    async initShopId() {
      if (this.currentShopId) {
        // 有shopId，直接加载数据
        this.loadData()
      }
    },

    // 刷新shopId（不依赖store）
    async refreshShopId() {
      try {
        // 避免重复调用
        if (this.isRefreshingShopId) {
          return;
        }
        
        this.isRefreshingShopId = true;
        
        
        // 直接调用API获取用户信息
        const userRes = await getInfo();
        if (userRes.code !== 200) {
          throw new Error('获取用户信息失败');
        }
        
        // 获取商家信息
        const shopRes = await getShopInfo(userRes.data.userID);
        if (shopRes.code !== 200) {
          throw new Error('获取商家信息失败');
        }
        
        // 直接设置到本地变量
        this.localShopId = shopRes.data.id;
      
        
        // 重新加载数据
        this.loadData();
        
      } catch (error) {
        console.error('刷新shopId失败:', error);
        
        // 根据错误类型处理
        if (error.message.includes('获取用户信息失败')) {
          this.$message.error('用户信息获取失败，请重新登录');
          this.$router.push('/login');
        } else if (error.message.includes('获取商家信息失败')) {
          this.$message.error('商家信息获取失败，请检查权限');
        } else {
          this.$message.error('系统错误，请稍后重试');
        }
      } finally {
        this.isRefreshingShopId = false;
      }
    },
    
    // 加载数据
    async loadData() {
      // 确保有shopId后再调用
      if (!this.currentShopId) {
      
        return;
      }

      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        }
        
        const response = await getDeliveryFeeRuleList(params)
        if (response.code === 200) {
          this.tableData = response.rows || []
          this.pagination.total = response.total || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        this.$message.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handleSearch() {
      this.pagination.currentPage = 1
      this.loadData()
    },
    
    // 重置搜索
    handleReset() {
      this.searchForm = {
        ruleId: '',
        isActive: ''
      }
      this.pagination.currentPage = 1
      this.loadData()
    },
    
    // 刷新
    handleRefresh() {
      this.loadData()
    },
    
    // 新增
    handleAdd() {
      this.isEdit = false
      this.dialogTitle = '新增配送费规则'
      this.resetForm()
      this.dialogVisible = true
    },
    
    // 编辑
    handleEdit(row) {
      this.isEdit = true
      this.dialogTitle = '编辑配送费规则'
      this.formData = { ...row }
      this.formData.noLimit = !row.maxDistance
      this.dialogVisible = true
    },
    
    // 删除
    async handleDelete(row) {
      try {
        await this.$confirm('确定要删除该配送费规则吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteDeliveryFeeRule(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.loadData()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    
    // 批量删除
    async handleBatchDelete() {
      try {
        await this.$confirm(`确定要删除选中的 ${this.selectedIds.length} 条配送费规则吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await deleteDeliveryFeeRuleBatch(this.selectedIds)
        if (response.code === 200) {
          this.$message.success('批量删除成功')
          this.selectedIds = []
          this.loadData()
        } else {
          this.$message.error(response.msg || '批量删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },
    
    // 切换状态
    async handleToggleStatus(row) {
      try {
        const action = row.isActive === 1 ? '禁用' : '启用'
        await this.$confirm(`确定要${action}该配送费规则吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        let response
        if (row.isActive === 1) {
          response = await disableDeliveryFeeRule(row.id)
        } else {
          response = await enableDeliveryFeeRule(row.id)
        }
        
        if (response.code === 200) {
          this.$message.success(`${action}成功`)
          this.loadData()
        } else {
          this.$message.error(response.msg || `${action}失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('切换状态失败:', error)
          this.$message.error('切换状态失败')
        }
      }
    },
    
    // 选择变化
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    
    // 分页大小变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },
    
    // 当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadData()
    },
    
    // 重置表单
    resetForm() {
      this.formData = {
        id: null,
        ruleId: '',
        shopId: this.currentShopId, // 使用动态获取的shopId
        baseDistance: 3,
        baseFee: 5,
        extraUnitDistance: 1,
        extraUnitFee: 2,
        maxDistance: 10,
        isActive: 1,
        noLimit: false
      }
      this.$nextTick(() => {
        this.$refs.formRef && this.$refs.formRef.clearValidate()
      })
    },
    
    // 无限制变化
    handleNoLimitChange(val) {
      if (val) {
        this.formData.maxDistance = null
      } else {
        this.formData.maxDistance = 10
      }
    },
    
    // 检查规则名称
    async checkRuleName() {
      if (!this.formData.ruleId || !this.formData.shopId) return
      
      try {
        const params = {
          ruleId: this.formData.ruleId,
          shopId: this.formData.shopId,
          excludeId: this.isEdit ? this.formData.id : null
        }
        
        const response = await checkRuleName(params)
        if (response.code === 200 && !response.data) {
          this.$message.warning('规则名称已存在，请更换')
        }
      } catch (error) {
        console.error('检查规则名称失败:', error)
      }
    },
    
    // 提交表单
    async handleSubmit() {
      try {
        await this.$refs.formRef.validate()
        
        this.submitLoading = true
        
        // 处理无限制的情况
        if (this.formData.noLimit) {
          this.formData.maxDistance = null
        }
        
        let response
        if (this.isEdit) {
          response = await updateDeliveryFeeRule(this.formData)
        } else {
          response = await addDeliveryFeeRule(this.formData)
        }
        
        if (response.code === 200) {
          this.$message.success(this.isEdit ? '更新成功' : '新增成功')
          this.dialogVisible = false
          this.loadData()
        } else {
          this.$message.error(response.msg || (this.isEdit ? '更新失败' : '新增失败'))
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error('提交失败')
      } finally {
        this.submitLoading = false
      }
    },
    
    // 对话框关闭
    handleDialogClose() {
      this.resetForm()
    },
    
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    },
    
    // 打开计算器
    openCalculator() {
      this.calculatorVisible = true
      this.calculationResult = null
    },
    
    // 计算配送费
    async calculateDeliveryFee() {
      if (!this.calculatorForm.distance) {
        this.$message.warning('请输入配送距离')
        return
      }
      
      this.calculateLoading = true
      try {
        const params = {
          shopId: this.currentShopId, // 使用动态获取的shopId
          distance: this.calculatorForm.distance
        }
        
        const response = await calculateDeliveryFee(params)
        if (response.code === 200) {
          this.calculationResult = response.data
        } else {
          this.$message.error(response.msg || '计算失败')
        }
      } catch (error) {
        this.$message.error('计算配送费失败')
      } finally {
        this.calculateLoading = false
      }
    }
  }
}
</script>

<style scoped>
.delivery-fee-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
}

.page-desc {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.table-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.unit-text {
  margin-left: 8px;
  color: #909399;
}

.calculation-example {
  background: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 13px;
  color: #606266;
}

.calculation-example p {
  margin: 4px 0;
}

.calculator-content {
  padding: 20px;
}

.calculation-result {
  margin-top: 20px;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.result-label {
  color: #606266;
}

.result-value {
  font-weight: bold;
  color: #303133;
}

.result-value.price {
  color: #f56c6c;
  font-size: 18px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .delivery-fee-container {
    padding: 10px;
  }
  
  .action-bar {
    flex-direction: column;
  }
  
  .search-form {
    display: block;
  }
  
  .search-form .el-form-item {
    display: block;
    margin-bottom: 15px;
  }
}
</style>
